<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="货品编号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入货品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前库存" prop="currentInventory">
        <el-input
          v-model="queryParams.currentInventory"
          placeholder="请输入当前库存"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ledger:details:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="inventoryQueryId" />
      <el-table-column label="货品编号" align="center" prop="productCode" />
      <el-table-column label="货品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="productModel" />
      <el-table-column label="单位" align="center" prop="dictLabel" />
      <el-table-column label="货品类型" align="center" prop="productTypeName" />
      <el-table-column label="当前库存" align="center" prop="currentInventory" />
      <el-table-column label="库存上限" align="center" prop="inventoryUpperLimit" />
      <el-table-column label="库存下限" align="center" prop="inventoryLowerLimit" />
      
      <el-table-column label="低于下限" align="center" prop="minusLowerLimit" >
        <template slot-scope="scope">
        <span :style="{ color: 'red' }">{{ calculatePercentage1(scope.row.currentInventory, scope.row.inventoryLowerLimit) }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="高于上限" align="center" prop="maxusUpperLimit" >
        <template slot-scope="scope">
        <span :style="{ color: 'red' }">{{ calculatePercentage2(scope.row.currentInventory,scope.row.inventoryUpperLimit) }}%</span>
      </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { listDetails } from "@/api/ledger/details";
import { findSelect } from "@/api/product/type";


export default {
  name: "Details",
  data() {
    return {
      //查询下拉列表框
      selectOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存预警表格数据
      detailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,
        currentInventory: null,
        productTypeCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.fetchItems();
  },
  methods: {
     calculatePercentage1(currentValue, limitValue) {
      if (limitValue === 0) return 0; // 防止除以零
      return Math.ceil(((limitValue  - currentValue) / limitValue * 100)).toFixed(2);
    },
    calculatePercentage2(currentValue, limitValue) {
      if (limitValue === 0) return 0; // 防止除以零
      return Math.ceil(((limitValue - currentValue) / limitValue * 100)).toFixed(2);
    },
    /** 查询库存预警列表 */
    getList() {
      this.loading = true;
      listDetails(this.queryParams).then(response => {
        this.detailsList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.detailsList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryQueryId: null,
        productCode: null,
        currentInventory:null,
        inventoryUpperLimit: null,
        inventoryLowerLimit: null,
        productName: null,
        productTypeName: null,
        productModel: null,
        dictLabel:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryQueryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ledger/details/export', {
        ...this.queryParams
      }, `details_${new Date().getTime()}.xlsx`)
    },
    async fetchItems() {
      try {
        const response = await findSelect();
        console.log('Response from findSelect:', response);
        if (Array.isArray(response)) {
          this.selectOptions = await this.convertToSelectOptions(response);
          console.log('Converted selectOptions:', this.selectOptions);
        } else {
          console.error('Expected an array, but got:', response);
        }
      } catch (error) {
        console.error('Error fetching items:', error);
      }
    },
    async convertToSelectOptions(data) {
      if (!Array.isArray(data)) {
        console.error('Expected an array, but got:', data);
        return [];
      }

      // 创建一个映射，用于快速查找父项
      const itemMap = new Map(data.map(item => [item.productTypeCode, item]));
      // 创建一个数组，用于存储所有项
      const allItems = [];

      data.forEach(async (item) => {
        allItems.push(await this.createSelectOption(item, itemMap));
      });

      return allItems;
    },
    async createSelectOption(item, itemMap) {
      const fullPathName = await this.getFullPathName(item, itemMap);
      return {
        productTypeCode: item.productTypeCode,
        productTypeName: item.productTypeName,
        fullPathName: fullPathName
      };
    },
    async getFullPathName(item, itemMap) {
      let pathName = item.productTypeName;
      let currentItem = item;

      while (currentItem.parentId !== null) {
        const parentItem = itemMap.get(currentItem.parentId);
        if (parentItem) {
          pathName = `${parentItem.productTypeName} / ${pathName}`;
          currentItem = parentItem;
        } else {
          break;
        }
      }

      return pathName;
    }
  }
};
</script>
